import React, { useEffect } from "react";
import { Button, Drawer, Form, Input } from "antd";
import { $add, $getOne, $update } from "../../apis/roleListApi";

export default function AddRole({ open, setOpen, loadList, keyId, setkeyId }) {
  let [form] = Form.useForm();
  useEffect(() => {
    if (keyId !== 0) {
      $getOne(keyId).then((res) => {
        form.setFieldsValue({ username: res.name });
      });
    }
  }, [keyId]);
  const onFinish = (values) => {
    if (keyId) {
      $update({ ...values, key: keyId }).then((res) => {
        loadList();
      });
    } else {
      $add(values).then((r) => {
        loadList();
        clear();
        alert("添加成功");
        loadList();
        onClose();
      });
    }
  };
  const clear = () => {
    form.resetFields();
  };
  const onClose = () => {
    clear();
    setkeyId(0);
    setOpen(false);
  };

  return (
    <Drawer
      title={keyId > 0 ? "修改信息" : "添加角色"}
      placement="right"
      onClose={onClose}
      open={open}
    >
      <Form
        form={form}
        name="basic"
        labelCol={{
          span: 4,
        }}
        wrapperCol={{
          span: 20,
        }}
        style={{
          maxWidth: 600,
        }}
        onFinish={onFinish}
        autoComplete="off"
      >
        <Form.Item
          label="名字"
          name="username"
          rules={[
            {
              required: true,
              message: "请输入名字!",
            },
          ]}
        >
          <Input />
        </Form.Item>
        <Form.Item label="keyId" name="key" hidden>
          <Input />
        </Form.Item>

        <Form.Item
          wrapperCol={{
            offset: 4,
            span: 16,
          }}
        >
          <Button type="primary" htmlType="submit">
            {keyId > 0 ? "修改" : "添加"}
          </Button>
          <Button onClick={clear}>取消</Button>
        </Form.Item>
      </Form>
    </Drawer>
  );
}
